#include <stdio.h>
#include <stdlib.h>
//#include <malloc.h>
#include "list.h"

static void copyToNode(Item item,Node *pnode);

BOOL createList(List *plist)
{
	*plist = NULL;
	return TRUE;
}

BOOL isFull(const List *plist)
{
	Node *pt;
	if (isEmpty(plist))
		return FALSE;

	pt = (Node *) malloc(sizeof(Node));
	if (pt == NULL){
		return TRUE;
	}
	free(pt);
	return FALSE;
}

BOOL isEmpty(const List *plist)
{
	if (*plist == NULL)
		return TRUE;
	return FALSE;
}

int list_length(const List *plist)
{
	int count = 0;
	Node *pnode = *plist;

	while(pnode != NULL){
		count++;
		pnode = pnode->next;
	}
	return count;
}

BOOL addItem(List *plist,const Item item)
{
	Node *pnew;
	Node *scan = *plist;

	pnew = (Node *)malloc(sizeof(Node));
	if (pnew == NULL){
		return FALSE;
	}
	copyToNode(item,pnew);
	pnew->next = NULL;
	if (*plist == NULL){
		*plist = pnew;
		return TRUE;
	}
	while(scan->next != NULL){
		scan = scan->next;
	}
	scan->next = pnew;
	return TRUE;
}

void traverse(const List *plist,Pfun pfun)
{
	Node * psave = *plist;
	while(psave != NULL){
		pfun(psave->item);
		psave = psave->next;	
	}
}

void destroyList(List *plist)
{
	Node *psave;
	while(*plist != NULL){
		psave = (*plist)->next;
		free(*plist);
		*plist = psave;
	}
}

static void copyToNode(Item item,Node *pnode)
{
	pnode->item = item;
}

